//
//  FTRulerSlider.m
//  FashionTech
//
//  Created by JackieYip on 16/5/15.
//  Copyright © 2016年 mondial-d. All rights reserved.
//

#import "FTRuler.h"
#import "FTTextField.h"
#import "NSString+Verifying.h"
#import "FTInternationalization_Macro.h"
#import "FTMacro_Screen.h"

#define dialColorGrayscale 0.789 //刻度的颜色灰度
#define textColorGrayscale 0.629 //文字的颜色灰度
#define textRulerFont [UIFont systemFontOfSize:9]

#define kUnitInch   FTLocalizedStringInLocalizable(@"inch")
#define kUnitCM     FTLocalizedStringInLocalizable(@"cm")
#define kUnitKG     FTLocalizedStringInLocalizable(@"kg")
#define kUnitLb     FTLocalizedStringInLocalizable(@"lb")


static CGFloat const kCmConefficientPerInch = 2.54;     // 1 inch = 2.54 cm
static CGFloat const kKgConefficientPerLb = 0.45359237; // 1 lb = 0.45359237 kg

@interface FTRulerView : UIView
@property (assign, nonatomic, readwrite) int minValue;
@property (assign, nonatomic, readwrite) int maxValue;

@property (assign, nonatomic, readwrite) int shortStepsCountInLongStep; // 每个大刻度里小刻度的个数
// 长刻度条 长度
@property (assign, nonatomic, readwrite) int dialLong;
// 短刻度条 长度
@property (assign, nonatomic, readwrite) int dialShort;
// 刻度条 间距
@property (assign, nonatomic, readwrite) CGFloat dialGap;
@property (strong, nonatomic, readwrite) NSString *currentUnit;
@property (assign, nonatomic, readwrite) FTRulerUnitStatus unitStatus;
@end

@implementation FTRulerView
- (void)drawRect:(CGRect)rect
{
    CGFloat lineCenterX = _dialGap;
    CGFloat shortLineY = rect.size.height - _dialShort;
    CGFloat longLineY = rect.size.height - _dialLong;
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor darkGrayColor].CGColor);
    CGContextSetLineWidth(context, 1/[UIScreen mainScreen].scale);
    CGContextSetLineCap(context, kCGLineCapButt);
    
    if (_unitStatus == FTRulerUnitStatus_englishSystem) {  // 英制单位
        for (int i = 0; i <= _shortStepsCountInLongStep; i++)
        {
            CGContextMoveToPoint(context, lineCenterX * i, 0); // 大或小 刻度 起点
            if (i%_shortStepsCountInLongStep == 0) {
                NSString *Num = [NSString stringWithFormat:@"%d %@", _minValue, _currentUnit];
                NSDictionary *attribute = @{NSFontAttributeName:textRulerFont, NSForegroundColorAttributeName:[UIColor colorWithWhite:textColorGrayscale alpha:1]};
                CGFloat width = [Num boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:0 attributes:attribute context:nil].size.width;
                
                [Num drawInRect:CGRectMake(lineCenterX * i - width/2, _dialLong, width, 14) withAttributes:attribute];
                CGContextAddLineToPoint(context, lineCenterX * i, _dialLong);    // 大刻度 终点
            }
            else
                CGContextAddLineToPoint(context, lineCenterX * i, _dialShort); // 小刻度 终点
            CGContextStrokePath(context);   // 绘制
        }
    }
    else if (_unitStatus == FTRulerUnitStatus_metricSystem){  // 公制单位
        CGFloat bottomY = rect.size.height;
        for (int i = 0; i <= _shortStepsCountInLongStep; i++)
        {
            if (i%_shortStepsCountInLongStep == 0) {
                NSString *Num = [NSString stringWithFormat:@"%d %@", _minValue, _currentUnit];
                NSDictionary *attribute = @{NSFontAttributeName:textRulerFont, NSForegroundColorAttributeName:[UIColor colorWithWhite:textColorGrayscale alpha:1]};
                CGFloat width = [Num boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:0 attributes:attribute context:nil].size.width;
                
                [Num drawInRect:CGRectMake(lineCenterX * i - width/2, longLineY-14, width, 14) withAttributes:attribute];
                CGContextMoveToPoint(context, lineCenterX * i, longLineY);    // 大刻度 起点
            }
            else
                CGContextMoveToPoint(context, lineCenterX * i, shortLineY); // 小刻度 起点
            
            CGContextAddLineToPoint(context, lineCenterX * i, bottomY); // 大或小 刻度 终点
            CGContextStrokePath(context);   // 绘制
        }
    }
}
@end

#pragma mark - FTHeaderRulerView

@interface FTHeaderRulerView : UIView
@property (assign, nonatomic, readwrite) int minValue;
@property (strong, nonatomic, readwrite) NSString *currentUnit;
// 刻度条 间距
@property (assign, nonatomic, readwrite) int dialLong;
@property (assign, nonatomic, readwrite) FTRulerUnitStatus unitStatus;

@end

@implementation FTHeaderRulerView

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    //    CGContextSetStrokeColorWithColor(context, [UIColor darkGrayColor].CGColor);
    CGContextSetRGBStrokeColor(context, dialColorGrayscale, dialColorGrayscale, dialColorGrayscale, 1);//设置线的颜色, 如果不设置默认是黑色的
    CGContextSetLineWidth(context, 1/[UIScreen mainScreen].scale);
    CGContextSetLineCap(context, kCGLineCapButt);
    // fix 最小值10以下 起点刻度的显示 bug
    NSString *Num = _minValue > 10 ? [NSString stringWithFormat:@"%d %@", _minValue, _currentUnit] : [NSString stringWithFormat:@"  %d %@", _minValue, _currentUnit];
    NSDictionary *attribute = @{NSFontAttributeName : textRulerFont, NSForegroundColorAttributeName : [UIColor colorWithWhite:textColorGrayscale alpha:1]};
    CGFloat width = [Num boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:0 attributes:attribute context:nil].size.width;
    
    if (_unitStatus == FTRulerUnitStatus_englishSystem) {  // 英制单位
        [Num drawInRect:CGRectMake(rect.size.width - width/2, _dialLong, width, 14) withAttributes:attribute];
        CGContextMoveToPoint(context, rect.size.width, 0); // 大刻度 起点
        CGContextAddLineToPoint(context, rect.size.width, _dialLong); // 大刻度 终点
        CGContextStrokePath(context); // 绘制
    }
    else if (_unitStatus == FTRulerUnitStatus_metricSystem) {
        [Num drawInRect:CGRectMake(rect.size.width - width/2, rect.size.height - _dialLong - 14, width, 14) withAttributes:attribute];
        CGContextMoveToPoint(context, rect.size.width, rect.size.height - _dialLong); // 大刻度 起点
        CGContextAddLineToPoint(context, rect.size.width, rect.size.height); // 大刻度 终点
        CGContextStrokePath(context); // 绘制
    }
}

@end

@interface FTFootRulerView : UIView
@property (assign, nonatomic, readwrite) int maxValue;
@property (strong, nonatomic, readwrite) NSString *currentUnit;

@property (assign, nonatomic, readwrite) int dialLong;
@property (assign, nonatomic, readwrite) FTRulerUnitStatus selectedUnitIndex;
@end

@implementation FTFootRulerView

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    //    CGContextSetStrokeColorWithColor(context, [UIColor darkGrayColor].CGColor);
    CGContextSetRGBStrokeColor(context, dialColorGrayscale, dialColorGrayscale, dialColorGrayscale, 1);//设置线的颜色, 如果不设置默认是黑色的
    CGContextSetLineCap(context, kCGLineCapButt);
    
    NSString *Num = [NSString stringWithFormat:@"%d %@", _maxValue, _currentUnit];
    NSDictionary *attribute = @{NSFontAttributeName : textRulerFont, NSForegroundColorAttributeName : [UIColor colorWithWhite:textColorGrayscale alpha:1]};
    CGFloat width = [Num boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:0 attributes:attribute context:nil].size.width;
    
    if (_selectedUnitIndex == FTRulerUnitStatus_englishSystem) {  // 英制单位
        [Num drawInRect:CGRectMake(- width/2, _dialLong, width, 14) withAttributes:attribute];
        CGContextMoveToPoint(context, 0, 0); // 大刻度 起点
        CGContextAddLineToPoint(context, 0, _dialLong); // 大刻度 终点
        CGContextStrokePath(context); // 绘制
    }
    else if (_selectedUnitIndex == FTRulerUnitStatus_metricSystem) {
        [Num drawInRect:CGRectMake(- width/2, rect.size.height - _dialLong - 14, width, 14) withAttributes:attribute];
        CGContextMoveToPoint(context, 0, rect.size.height - _dialLong); // 大刻度 起点
        CGContextAddLineToPoint(context, 0, rect.size.height); // 大刻度 终点
        CGContextStrokePath(context); // 绘制
    }
}

@end

#pragma mark - FTRuler

@interface FTRuler () <UIScrollViewDelegate, UITextFieldDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property (strong, nonatomic, readwrite) UILabel *titleLabel;
@property (strong, nonatomic, readwrite) FTTextField *valueTF;
@property (strong, nonatomic, readwrite) UISegmentedControl *rulerTypeSegment;
@property (strong, nonatomic, readwrite) UICollectionView *collectionView;
@property (strong, nonatomic, readwrite) UIView *blackLine;
@property (strong, nonatomic, readwrite) UIView *bottomLine;

@property (assign, nonatomic, readwrite) BOOL scrollByHand;

@property (strong, nonatomic, readwrite) NSString *title;
@property (strong, nonatomic, readwrite) NSString *currentUnit;
@property (assign, nonatomic, readwrite) CGFloat realValue;
// 实际显示的最大、最小值
@property (assign, nonatomic, readwrite) int minValue;
@property (assign, nonatomic, readwrite) int maxValue;
// 保存初始化的最大、最小值
@property (assign, nonatomic, readwrite) double adjustMinValue;
@property (assign, nonatomic, readwrite) double adjustMaxValue;

@property (assign, nonatomic, readwrite) int valuePerShortStep; // 每个小刻度的值
@property (assign, nonatomic, readwrite) int shortStepsCountInLongStep; // 每个大刻度里小刻度的个数
@property (assign, nonatomic, readwrite) int longStepsCount; // 所有大刻度个数

// 长刻度条 长度
@property (assign, nonatomic, readwrite) int dialLong;
// 短刻度条 长度
@property (assign, nonatomic, readwrite) int dialShort;
// 小刻度条 间距
@property (assign, nonatomic, readwrite) double dialGap;

@property (assign, nonatomic, readwrite) FTRulerUnitStatus unitStatus;
@property (assign, nonatomic, readwrite) FTRulerUnitType unitType;
@property (assign, nonatomic, readwrite) BOOL didChangeRulerTypeFlag;
@property (strong, nonatomic, readwrite) NSString *editingTextFieldTextBeforeChange;
@end

@implementation FTRuler
- (instancetype)initWithFrame:(CGRect)frame
                        title:(NSString *)title
                  currentUnit:(NSString *)currentUnit
                 currentValue:(double)currentValue             // 初始值
                     minValue:(int)minValue
                     maxValue:(int)maxValue
                   unitStatus:(FTRulerUnitStatus)unitStatus        // 选中的单位下标
                     unitType:(FTRulerUnitType)unitType     // 单位类型
                   needHeadBG:(BOOL)needHeadBG              // 是否需要上部背景
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor clearColor];
        self.scrollByHand = NO;
        // Value
        self.unitStatus = unitStatus;
        self.title = title;
        self.unitType = unitType;
        self.currentUnit = currentUnit;
        
        self.valuePerShortStep = 1;
        self.dialLong = 18;
        self.dialShort = 9;
        
        [self innerSetupValueWithMinValue:minValue maxValue:maxValue];
        
        // UI
        [self innerInitUIWithInitValue:currentValue needHeadBG:needHeadBG];
    }
    return self;
}

- (void)innerSetupValueWithMinValue:(int)minValue maxValue:(int)maxValue
{
    // 英制
    if (self.unitStatus == FTRulerUnitStatus_englishSystem) {
        int maxValueRemainder = 0;
        if (self.unitType == FTRulerUnitType_kgAndLb) {
            NSString *dialGapDivisor = [NSString stringWithFormat:@"%.1f", kKgConefficientPerLb];
            self.dialGap = 12 * [dialGapDivisor floatValue];
            self.shortStepsCountInLongStep = 10;
            self.adjustMinValue = minValue / kKgConefficientPerLb;
            self.adjustMaxValue = maxValue / kKgConefficientPerLb;
            maxValueRemainder = maxValue / kKgConefficientPerLb != 0 ? 1 : 0;
        }
        else if (self.unitType == FTRulerUnitType_cmAndInch) {
            NSString *dialGapDivisor = [NSString stringWithFormat:@"%.1f", kCmConefficientPerInch];
            self.dialGap = 6 * [dialGapDivisor floatValue];
            self.shortStepsCountInLongStep = 12;
            self.adjustMinValue = minValue / kCmConefficientPerInch;
            self.adjustMaxValue = maxValue / kCmConefficientPerInch;
            maxValueRemainder = maxValue / kCmConefficientPerInch != 0 ? 1 : 0;
        }
        
        self.minValue = (int)(_adjustMinValue/_shortStepsCountInLongStep) * _shortStepsCountInLongStep;
        self.maxValue = (int)((_adjustMaxValue/_shortStepsCountInLongStep) + maxValueRemainder) * _shortStepsCountInLongStep;
    }
    // 公制
    else if (self.unitStatus == FTRulerUnitStatus_metricSystem) {
        if (self.unitType == FTRulerUnitType_kgAndLb) {
            self.dialGap = 12;
        }
        else if (self.unitType == FTRulerUnitType_cmAndInch) {
            self.dialGap = 6;
        }
        self.shortStepsCountInLongStep = 10;
        self.adjustMinValue = self.minValue = (int)(minValue/_shortStepsCountInLongStep) * _shortStepsCountInLongStep;
        self.adjustMaxValue = self.maxValue = (int)(maxValue/_shortStepsCountInLongStep) * _shortStepsCountInLongStep;
        self.longStepsCount = (_maxValue - _minValue)/_valuePerShortStep/_shortStepsCountInLongStep;
    }
}

- (void)innerInitUIWithInitValue:(double)initValue needHeadBG:(BOOL)needHeadBG
{
    // 头背景
    UIView *header = [[UIView alloc] init];
    header.backgroundColor = [UIColor colorWithWhite:0 alpha:0.1];
    [self addSubview:header];
    
    // 名称Label
    NSString *title = [NSString stringWithFormat:@"%@ ", _title];
    CGFloat height = [_title boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size.height;
    CGFloat width = [title sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]}].width + 20;
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, width, height)];
    self.titleLabel.font = [UIFont systemFontOfSize:14];
    self.titleLabel.numberOfLines = 0;
    self.titleLabel.textAlignment = NSTextAlignmentLeft;
    self.titleLabel.text = title;
    self.titleLabel.textColor = [UIColor blackColor];
    [self addSubview:_titleLabel];
    
    // 输入框
    self.valueTF = [[FTTextField alloc] initWithFrame:CGRectMake(0, 0, 120, 30)];
    self.valueTF.center = CGPointMake(self.frame.size.width/2, CGRectGetMinY(_titleLabel.frame) + self.valueTF.frame.size.height/2);
    self.valueTF.defaultTextAttributes = @{NSUnderlineColorAttributeName:[UIColor blackColor], NSUnderlineStyleAttributeName:@(1), NSFontAttributeName:[UIFont systemFontOfSize:18], NSForegroundColorAttributeName:[UIColor grayColor]};
    self.valueTF.textAlignment = NSTextAlignmentCenter;
    self.valueTF.delegate = self;
    self.valueTF.keyboardType = UIKeyboardTypeNumberPad;
    
    self.valueTF.attributedPlaceholder = [[NSAttributedString alloc]initWithString:FTLocalizedStringInLocalizable(@"滑动标尺或输入")
                                                                        attributes:@{NSUnderlineColorAttributeName:[UIColor lightGrayColor],
                                                                                     NSUnderlineStyleAttributeName:@(1),
                                                                                     NSFontAttributeName:[UIFont systemFontOfSize:12],
                                                                                     NSForegroundColorAttributeName:[UIColor grayColor]}];
    
    [self addSubview:_valueTF];
    
    if (self.unitType == FTRulerUnitType_cmAndInch) {
        [self addUnitSegmentWithFirstUnit:FTLocalizedStringInLocalizable(@"厘米") secondUnit:FTLocalizedStringInLocalizable(@"英寸") selectedUnitIndex:self.unitStatus];
    }
    else if (self.unitType == FTRulerUnitType_kgAndLb) {
        [self addUnitSegmentWithFirstUnit:FTLocalizedStringInLocalizable(@"千克") secondUnit:FTLocalizedStringInLocalizable(@"磅") selectedUnitIndex:self.unitStatus];
    }
    
    //标尺
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    [flowLayout setSectionInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    CGFloat collectionHeight = self.frame.size.height - CGRectGetMaxY(_valueTF.frame) - 10;
    _collectionView  =[[UICollectionView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_valueTF.frame), self.bounds.size.width, collectionHeight) collectionViewLayout:flowLayout];
    self.backgroundColor = [UIColor whiteColor];
    _collectionView.backgroundColor = [UIColor whiteColor];
    
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"systemCell"];
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"customCell"];
    
    _collectionView.bounces = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [self addSubview:_collectionView];
    
    // 准线
    _blackLine = [[UIView alloc] initWithFrame:CGRectMake(self.bounds.size.width/2-1/[UIScreen mainScreen].scale, CGRectGetMinY(_collectionView.frame), 1, _collectionView.frame.size.height)];
    _blackLine.backgroundColor = [UIColor blackColor];
    [self addSubview:_blackLine];
    
    // 设置头背景
    if (needHeadBG) {
        header.frame = CGRectMake(0, CGRectGetMinY(self.frame), self.bounds.size.width, CGRectGetMinY(_collectionView.frame) - CGRectGetMinY(self.frame));
    }
    else
        header.frame = CGRectZero;
    
    // 皮尺顶线
    UIView *rulerTopLine = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMinY(_collectionView.frame), self.bounds.size.width, 1/[UIScreen mainScreen].scale)];
    rulerTopLine.backgroundColor = [UIColor grayColor];
    [self addSubview:rulerTopLine];
    
    // 皮尺底线
    _bottomLine = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_collectionView.frame), self.bounds.size.width, 1/[UIScreen mainScreen].scale)];
    _bottomLine.backgroundColor = [UIColor grayColor];
    [self addSubview:_bottomLine];
    
    if (initValue > 0) {
        self.valueTF.placeholder = nil;
        [self setRealValue:initValue animated:NO];
    }
}

- (void)addUnitSegmentWithFirstUnit:(NSString *)firstUnit secondUnit:(NSString *)secondUnit selectedUnitIndex:(FTRulerUnitStatus)selectedUnitIndex
{
    if (firstUnit.length > 0 && secondUnit.length > 0) {
        //更换皮尺类型（厘米/英寸）
        self.rulerTypeSegment = [[UISegmentedControl alloc] initWithItems:@[firstUnit, secondUnit]];
        CGFloat segmentWidth = 100;
        self.rulerTypeSegment.frame = CGRectMake(kScreenWidth - segmentWidth - 10, 0, segmentWidth, 25);
        CGPoint center = self.rulerTypeSegment.center;
        center.y = _titleLabel.center.y;
        self.rulerTypeSegment.center = center;
        self.rulerTypeSegment.selectedSegmentIndex = selectedUnitIndex;
        self.rulerTypeSegment.tintColor = [UIColor blackColor];
        [self.rulerTypeSegment addTarget:self action:@selector(didChangeRulerType:) forControlEvents:UIControlEventValueChanged];
        [self addSubview:_rulerTypeSegment];
    }
}

- (void)didChangeRulerType:(UISegmentedControl *)segment
{
    if (_scrollByHand)
        [self setRealValue:round(_collectionView.contentOffset.x/_dialGap) + _minValue animated:YES];
    
    self.unitStatus = segment.selectedSegmentIndex;
    self.didChangeRulerTypeFlag = YES;
    if (self.unitType == FTRulerUnitType_cmAndInch) {
        // 当前选中 英寸
        if (segment.selectedSegmentIndex == FTRulerUnitStatus_englishSystem) {
            [self becomeEnglishSystemRulerWithDivisor:kCmConefficientPerInch unitString:kUnitInch shortStepsCountInLongStep:12];
        }
        // 当前选中 厘米
        else if (segment.selectedSegmentIndex == FTRulerUnitStatus_metricSystem) {
            [self becomeMetricSystemRulerWithDivisor:kCmConefficientPerInch unitString:kUnitCM shortStepsCountInLongStep:10];
        }
    }
    else if (self.unitType == FTRulerUnitType_kgAndLb) {
        // 当前选中 磅
        if (segment.selectedSegmentIndex == FTRulerUnitStatus_englishSystem) {
            [self becomeEnglishSystemRulerWithDivisor:kKgConefficientPerLb unitString:kUnitLb shortStepsCountInLongStep:10];
        }
        // 当前选中 千克
        else if (segment.selectedSegmentIndex == FTRulerUnitStatus_metricSystem) {
            [self becomeMetricSystemRulerWithDivisor:kKgConefficientPerLb unitString:kUnitKG shortStepsCountInLongStep:10];
        }
    }
    [self.collectionView reloadData];
    
    if ([_delegate respondsToSelector:@selector(FTRulerSlider:didChangeRulerUnit:)]) {
        [_delegate FTRulerSlider:self didChangeRulerUnit:self.currentUnit];
    }
}

- (void)becomeEnglishSystemRulerWithDivisor:(double)divisor unitString:(NSString *)unitString shortStepsCountInLongStep:(int)shortStepsCountInLongStep
{
    NSString *dialGapDivisor = [NSString stringWithFormat:@"%.1f", divisor];
    self.dialGap = _dialGap * [dialGapDivisor floatValue];
    self.shortStepsCountInLongStep = shortStepsCountInLongStep;
    self.currentUnit = unitString;
    self.titleLabel.text = [NSString stringWithFormat:@"%@", _title];
    self.unitStatus = FTRulerUnitStatus_englishSystem;
    self.adjustMinValue = _adjustMinValue / divisor;
    self.adjustMaxValue = _adjustMaxValue / divisor;
    int maxValueRemainder = _adjustMaxValue / divisor != 0 ? 1 : 0;
    self.minValue = (int)(_adjustMinValue/_shortStepsCountInLongStep) * _shortStepsCountInLongStep;
    self.maxValue = (int)((_adjustMaxValue/_shortStepsCountInLongStep) + maxValueRemainder) * _shortStepsCountInLongStep;
    [self setRealValue:_realValue / divisor animated:YES];
}

- (void)becomeMetricSystemRulerWithDivisor:(double)divisor unitString:(NSString *)unitString shortStepsCountInLongStep:(int)shortStepsCountInLongStep
{
    NSString *dialGapDivisor = [NSString stringWithFormat:@"%.1f", divisor];
    self.dialGap = _dialGap / [dialGapDivisor floatValue];
    self.shortStepsCountInLongStep = shortStepsCountInLongStep;
    self.currentUnit = unitString;
    self.titleLabel.text = [NSString stringWithFormat:@"%@", _title];
    self.unitStatus = FTRulerUnitStatus_metricSystem;
    self.adjustMinValue = _adjustMinValue * divisor;
    self.adjustMaxValue = _adjustMaxValue * divisor;
    self.minValue = (int)(_adjustMinValue/_shortStepsCountInLongStep) * _shortStepsCountInLongStep;
    self.maxValue = (int)(_adjustMaxValue/_shortStepsCountInLongStep) * _shortStepsCountInLongStep;
    [self setRealValue:_realValue * divisor animated:YES];
}

- (void)setRealValue:(CGFloat)realValue
{
    [self setRealValue:realValue animated:NO];
}

- (void)setTitle:(NSString *)title
{
    _title = title;
    self.titleLabel.text = _title;
}

- (void)setRealValue:(double)realValue animated:(BOOL)animated
{
    // 低于最小值
    if (realValue < _minValue) {
        return;
        //        [self.collectionView setContentOffset:CGPointMake(0, 0) animated:YES];
        //        _realValue = 0;
    }
    // 大于最大值
    else if (realValue > _maxValue) {
        return;
        //        [self.collectionView setContentOffset:CGPointMake(_maxValue, 0) animated:YES];
        //        _realValue = _maxValue / _dialGap;
    }
    else
        _realValue = realValue;
    [self.collectionView setContentOffset:CGPointMake((int)(_realValue - _minValue) * _dialGap, 0) animated:YES];
    if (!_didChangeRulerTypeFlag) {
        if ([_delegate respondsToSelector:@selector(FTRulerSlider:ValueChange:)]) {
            [_delegate FTRulerSlider:self ValueChange:_realValue];
        }
    }
    else
        self.didChangeRulerTypeFlag = NO;
    
    // 推迟0.2秒后更新textField，使textField更新钝化、平稳
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _valueTF.text = [NSString stringWithFormat:@"%d",(int)((_realValue - _minValue)*_valuePerShortStep + _minValue)];
    });
}

#pragma mark - <UITextFieldDelegate>
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    textField.keyboardType = UIKeyboardTypeNumberPad;
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    if ([_delegate respondsToSelector:@selector(FTRulerSlider:saveFirstResponder:)])
        [_delegate FTRulerSlider:self saveFirstResponder:textField];
    textField.returnKeyType = UIReturnKeyNext;
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [textField removeTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    if ([_delegate respondsToSelector:@selector(discardFirstResponderInFTRulerSlider:)])
        [_delegate discardFirstResponderInFTRulerSlider:self];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    self.editingTextFieldTextBeforeChange = textField.text;
    if (![string isValidNumber])    // 输入必须为数字
        return NO;
    return YES;
}

- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField.markedTextRange)
        return;
    if ([textField.text integerValue] > _maxValue) {
        //        [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:FTLocalizedStringInLocalizable(@"最大值为%d"), _maxValue]];
        textField.text = _editingTextFieldTextBeforeChange;
    }
    // 为零时不更新： 编辑前的值 == 当前的值  == 0
    if (([textField.text integerValue] != [_editingTextFieldTextBeforeChange integerValue]) ||
        ([_editingTextFieldTextBeforeChange integerValue] != 0)) {
        textField.text = [textField.text stringFormatForPreviousZero];
        [self setRealValue:([_valueTF.text floatValue])/(CGFloat)_valuePerShortStep animated:YES];
    }
}

#pragma mark - <UICollectionViewDataSource & Delegate>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 2 + (int)((_maxValue - _minValue)/_shortStepsCountInLongStep);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.item == 0 || indexPath.item == (int)((_maxValue - _minValue)/_shortStepsCountInLongStep) + 1) {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"systemCell" forIndexPath:indexPath];
        for (UIView *subView in cell.contentView.subviews) {
            [subView removeFromSuperview];
        }
        
        if (indexPath.item == 0) {
            UIView *halfView = [[FTHeaderRulerView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width/2, collectionView.bounds.size.height)];
            FTHeaderRulerView *header = (FTHeaderRulerView *)halfView;
            header.backgroundColor = [UIColor whiteColor];
            header.minValue = _minValue;
            header.currentUnit = _currentUnit;
            header.unitStatus = _unitStatus;
            header.dialLong = _dialLong;
            [cell.contentView addSubview:header];
        }
        else
        {
            FTFootRulerView *footer = [[FTFootRulerView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width/2, collectionView.bounds.size.height)];
            footer.backgroundColor = [UIColor whiteColor];
            footer.maxValue = _maxValue;
            footer.currentUnit = _currentUnit;
            footer.selectedUnitIndex = _unitStatus;
            footer.dialLong = _dialLong;
            [cell.contentView addSubview:footer];
        }
        return cell;
    }
    else
    {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"customCell" forIndexPath:indexPath];
        for (UIView *subView in cell.contentView.subviews) {
            [subView removeFromSuperview];
        }
        
        FTRulerView *ruleView = [[FTRulerView alloc] initWithFrame:CGRectMake(0, 0, _dialGap * _shortStepsCountInLongStep, collectionView.bounds.size.height)];
        ruleView.backgroundColor = [UIColor whiteColor];
        ruleView.currentUnit = _currentUnit;
        ruleView.shortStepsCountInLongStep = _shortStepsCountInLongStep;
        ruleView.dialLong = _dialLong;
        ruleView.dialShort = _dialShort;
        ruleView.dialGap = _dialGap;
        ruleView.unitStatus = _unitStatus;
        [cell.contentView addSubview:ruleView];
        ruleView.minValue = (CGFloat)_valuePerShortStep * _shortStepsCountInLongStep * indexPath.item + _minValue;
        ruleView.maxValue = (CGFloat)_valuePerShortStep * _shortStepsCountInLongStep * (indexPath.item + 1) + _minValue;
        [ruleView setNeedsDisplay];
        return cell;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.item == 0 || indexPath.item == (int)((_maxValue - _minValue)/_shortStepsCountInLongStep + 1)) {
        return CGSizeMake(self.bounds.size.width/2, collectionView.bounds.size.height);
    }
    else
        return CGSizeMake(_dialGap * _shortStepsCountInLongStep, collectionView.bounds.size.height);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0.0;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0.0;
}

#pragma mark UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (_scrollByHand)
    {
        int value = scrollView.contentOffset.x/_dialGap;
        _valueTF.text = [NSString stringWithFormat:@"%d",(int)(value*_valuePerShortStep + _minValue)];
    }
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    _scrollByHand = YES;
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate)//拖拽时没有滑动动画
    {
        [self setRealValue:round(scrollView.contentOffset.x/_dialGap) + _minValue animated:YES];
    }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self setRealValue:round(scrollView.contentOffset.x/_dialGap) + _minValue animated:YES];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    _scrollByHand = NO;
}

@end
